package com.example.demo.netty.client;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {
    public static void main(String[] args) {
        // 客户端事件处理线程组
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            // 启动类以及配置事件处理器
            Bootstrap bootstrap =new Bootstrap();
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new NettyClientHandler());
                        }
                    });
            // 启动客户端并发起阻塞连接
            ChannelFuture channelFuture =bootstrap.connect("127.0.0.1",7000).sync();
            // 阻塞查询通道是否关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally{
            // 释放资源
            workGroup.shutdownGracefully();
        }

    }
}
